package com.zc.study.pay.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import org.simpleframework.xml.Order;
import org.springframework.http.HttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AliPay {
    //完成签名,生成预付款订单,返给前端app
    public Map<String,Object> order(Order order){

        //实例化客户端
        String APP_ID = AliData.APP_ID;
        String APP_PRIVATE_KEY = AliData.APP_PRIVATE_KEY;
        String charset = AliData.charset;
        String ALIPAY_PUBLIC_KEY = AliData.ALIPAY_PUBLIC_KEY;
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                APP_ID,//appid
                APP_PRIVATE_KEY,//私钥
                "json", //格式，仅支持json
                charset,//请求编码格式
                ALIPAY_PUBLIC_KEY,//应用公钥
                "RSA2");//签名算法类型，支持RSA2和RSA，推荐使用的是RSA2
        Map<String,Object> map = new HashMap<>();
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("内容");
        model.setSubject("标题");
        model.setOutTradeNo("唯一订单号（自己生成的)");
        model.setTimeoutExpress("30m");//一般用不到这个
        model.setTotalAmount("0.01");//这个嘛就是钱喽
        model.setProductCode("QUICK_MSECURITY_PAY");//商家和支付宝签约的产品码，为固定值
        request.setBizModel(model);
        request.setNotifyUrl("异步地址");//外网异步回调地址，是需要外网能够访问到的
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            map.put("data",response.getBody());//这里直接把订单信息给app端就好了，让他直接拿着去调起支付宝
            map.put("status","success");
            return map;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            map.put("status","fail");
            return map;
        }
    }

    //支付宝回调
    public String aliCall(HttpServletRequest request){
        String ALIPAYPUBLICKEY = AliData.ALIPAYPUBLICKEY;
        String charset = AliData.charset;
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = false;//验签不通过支付宝会一直回调你的异步回调
        try {
            flag = AlipaySignature.rsaCheckV1(params,
                    ALIPAYPUBLICKEY, //这里是支付宝公钥不是应用公钥
                    charset,"RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (flag){
            if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                //这里写业务逻辑，操作数据库等操作
                return "success";//成功返给支付宝成功就行了，
            }
        }
        return "error";

    }
}
